/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="deviceinfo-register-device">
    <el-dialog
      :title="$t('edge.deviceinfo.registerdevice')"
      :visible.sync="dialogVisible"
      width="33%"
      :close-on-click-modal="false">
      <div class="register-device-form" v-loading="loading" element-loading-spinner="el-icon-loading"
      :element-loading-background="loadingBg">
        <el-form ref="innerFormDom" :model="innerForm" :rules="updateRules" >
            <div class="register-device-info">
              <div class="tittle">{{$t('edge.deviceinfo.deviceinfo')}}</div>
              <el-form-item prop="agentid" :label="$t('edge.deviceinfo.deviceid')" label-width="21%">
                <el-input v-model="innerForm.agentid" autocomplete="off" disabled></el-input>
              </el-form-item>
              <el-form-item prop="secretkey" :label="$t('edge.deviceinfo.secretkey')" label-width="21%">
                <el-input v-model="innerForm.secretkey" autocomplete="off"></el-input>
                <el-button type="text" @click="generateDeviceKey">{{$t('edge.deviceinfo.generatesecretkey')}}</el-button>
              </el-form-item>
            </div>
        </el-form>
        <el-form ref="innerFormDom2" :model="innerForm" :rules="updateRules2" >
              <div class="register-platform-info">
                <div class="tittle">{{$t('edge.deviceinfo.platforminfo')}}</div>
                <el-form-item :label="$t('edge.deviceinfo.platformip')" label-width="21%">
                    <el-input v-model="innerForm.ip" autocomplete="off" disabled></el-input>
                </el-form-item>
                <el-form-item class="platport" prop="port" :label="$t('edge.deviceinfo.platport')" label-width="21%">
                    <el-input v-model="innerForm.port" autocomplete="off" :disabled="!isRegisterDev"></el-input>
                </el-form-item>
                <el-form-item class="username" prop="username" :label="$t('edge.deviceinfo.user')" label-width="21%">
                    <el-input v-model="innerForm.username" autocomplete="off" :disabled="!isRegisterDev"></el-input>
                </el-form-item>
                <el-form-item class="password" prop="password" :label="$t('edge.deviceinfo.password')" label-width="21%">
                    <el-input
                      type="password"
                      v-model="innerForm.password"
                      auto-complete="new-password"
                      :disabled="!isRegisterDev"
                      onpaste="return false" oncontextmenu="return false" oncopy="return false" oncut="return false"
                    ></el-input>
                </el-form-item>
              </div>
        </el-form>
      </div>
      <div
        slot="footer"
        class="dialog-footer">
          <el-checkbox v-model="isRegisterDev" :disabled="isfromatc">{{$t('edge.deviceinfo.registerdevice')}}</el-checkbox>
          <el-button @click="handleClose">{{$t('edge.button.Cancel')}}</el-button>
          <el-button type="primary" @click="handleUpdate()">{{$t('edge.button.update')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createRandomKey } from '../../../utils/index.js'
import { getMessageByCode } from '@/utils/responseMessage'
import { getInfoBySiteId, updateDeviceAuth, loginDeviceAuth, loginPlatform } from '@/api/system'
import { getErrorMesZh, getErrorMesEn } from '../../../utils/errorcode.js'
import { downloadDeviceInfo } from '@/api/param'
import { getTheme } from '../../../utils/auth.js'
import { setLoginInfo, getLoginInfo } from '../../login/loginInterface.js'
import { mapGetters } from 'vuex'
export default {
  name: 'registerDevice',
  data () {
    return {
      dialogVisible: false,
      loading: false,
      loadingBg: '#202940',
      innerForm: {},
      updateRules: {
        agentid: [
          { required: true, trigger: 'blur', message: this.$t('edge.deviceinfo.agentidnotnull') }
        ],
        secretkey: [
          // { required: true, trigger: 'blur', message: this.$t('edge.deviceinfo.secretkeynotnull') },
          // { min: 8, max: 16, message: this.$t('edge.deviceinfo.enterSecretkeylength'), trigger: 'blur' },
          {
            required: true,
            validator: this.validateSecretkey,
            trigger: 'blur'
          }
        ]
      },
      updateRules2: {
        port: [
          { required: true, trigger: 'blur', message: this.$t('edge.deviceinfo.portnotnull') }
        ],
        username: [
          { required: true, trigger: 'blur', message: this.$t('edge.deviceinfo.usernamenotnull') }
        ],
        password: [
          { required: true, trigger: 'blur', message: this.$t('edge.deviceinfo.passwordnotnull') }
        ]
      },
      isRegisterDev: false,
      token: ''
    }
  },
  computed: {
    ...mapGetters([
      'isfromatc'
    ])
  },
  methods: {
    show (customInfo) {
      this.customInfo = customInfo
      this.dialogVisible = true
      this.innerForm = {
        agentid: customInfo.intersectionid,
        secretkey: '',
        ip: customInfo.centerip.ip,
        // ip: '192.168.14.5',
        netcardfirstip: customInfo.netcard[0].ip,
        port: 10003,
        username: '',
        password: ''
      }
    },
    handleClose (done) {
      this.$refs.innerFormDom.clearValidate()
      this.$refs.innerFormDom2.clearValidate()
      this.dialogVisible = false
    },
    generateDeviceKey () {
      this.innerForm.secretkey = createRandomKey(8)
    },
    handleUpdate () {
      console.log(this.innerForm)
      this.$refs.innerFormDom.validate(valid => {
        if (valid) {
          if (!this.isRegisterDev) {
            this.loading = true
            this.updatePassword()
          } else {
            this.$refs.innerFormDom2.validate(valid2 => {
              if (valid2) {
                this.loading = true
                this.platformLogin().then(() => {
                  this.searchDeviceId()
                })
              }
            })
          }
        }
      })
    },
    updatePassword () {
      // 更新密钥
      return new Promise((resolve, reject) => {
        updateDeviceAuth(
          this.innerForm.agentid,
          this.innerForm.secretkey
        )
          .then(data => {
            this.loading = false
            if (data.data.success !== true) {
              this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
              return
            }
            // 更新密钥成功后认证类型缓存为2
            let info = getLoginInfo()
            if (info) {
              info = JSON.parse(info)
              info.auth = 2
              setLoginInfo(info)
            }
            this.$message.success(this.$t('edge.common.updatesucess'))
            resolve()
          })
          .catch(err => {
            this.loading = false
            this.$message.error(err)
            reject(err)
          })
      })
    },
    platformLogin () {
      // 平台登陆
      return new Promise((resolve, reject) => {
        loginPlatform(
          this.innerForm.username,
          this.innerForm.password,
          '',
          '',
          this.innerForm.ip,
          this.innerForm.port
        )
          .then(data => {
            if (data.data.success !== true) {
              this.loading = false
              if (data.data.code === '3009') {
                this.$message.error(this.$t('openatc.login.passerror'))
                return
              }
              if (data.data.code === '3001') {
                this.$message.error(this.$t('openatc.login.usernamenotexist'))
                return
              }
              this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
              return
            }
            this.token = data.data.data.token
            console.log(this.token)
            resolve(this.token)
          })
          .catch(err => {
            this.loading = false
            this.$message.error(err)
            reject(err)
          })
      })
    },
    searchDeviceId () {
      // 查询设备id
      return new Promise((resolve, reject) => {
        getInfoBySiteId(
          this.innerForm.agentid,
          this.innerForm.ip,
          this.innerForm.port,
          this.token)
          .then(data => {
            if (data.data.success !== true) {
              this.loading = false
              this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
              return
            }
            let devdata = data.data.data
            if (devdata.length > 1) {
              this.$message.error(this.$t('edge.deviceinfo.containsmultipledevices'))
              this.loading = false
            } else {
              let auth = devdata[0].auth
              if (auth !== 0) {
                this.$confirm(this.$t('edge.deviceinfo.registeredisupdate'), this.$t('edge.system.tips'), {
                  confirmButtonText: this.$t('edge.button.OK'),
                  cancelButtonText: this.$t('edge.button.Cancel'),
                  type: 'warning'
                }).then(() => {
                  this.updatePassword()
                }).catch(() => {
                  this.$message({
                    type: 'info',
                    message: this.$t('edge.deviceinfo.canceled')
                  })
                })
              } else {
                this.registerDevice()
              }
            }
            resolve()
          })
          .catch(err => {
            this.loading = false
            this.$message.error(err)
            reject(err)
          })
      })
    },
    registerDevice () {
      // 注册设备
      return new Promise((resolve, reject) => {
        loginDeviceAuth(
          this.innerForm.agentid,
          this.innerForm.secretkey,
          this.innerForm.netcardfirstip,
          this.innerForm.ip,
          this.innerForm.port,
          this.token
        )
          .then(data => {
            if (data.data.success !== true) {
              this.loading = false
              this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
              return
            }
            // this.$message.success(this.$t('edge.deviceinfo.loginsuccessful'))
            this.download()
            resolve()
          })
          .catch(err => {
            this.loading = false
            this.$message.error(err)
            reject(err)
          })
      })
    },
    download () {
      let customInfo = this.customInfo
      this.handleIpPortValue()
      downloadDeviceInfo(customInfo).then(data => {
        if (!data.data.success) {
          this.loading = false
          if (data.data.code === '4003') {
            this.$message.error(this.$t('edge.errorTip.devicenotonline'))
            return
          }
          if (data.data.code === '4002' && data.data.data.errorCode === '4209') {
            let success = data.data.data.content.success
            if (success !== 0) {
              let errormsg = 'openatccomponents.overview.putTscControlError' + success
              this.$message.error(this.$t(errormsg))
              return
            }
          }
          if (data.data.code === '4002') { // 错误应答
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              this.$message.error(getMessageByCode(data.data.data.errorCode, this.$i18n.locale))
            }
            if (data.data.data.errorCode === '4207') {
              // 信号机参数校验
              let codeList = data.data.data.content.errorCode
              if (codeList.length === 0) {
                this.$message.error(this.$t('edge.errorTip.saveParamFailed'))
                return
              }
              let errorMes = this.$t('edge.common.downloaderror')
              for (let code of codeList) {
                if (this.$i18n.locale === 'en') {
                  errorMes = getErrorMesEn(errorMes, code)
                } else {
                  errorMes = getErrorMesZh(errorMes, code)
                }
              }
              this.$message({
                message: errorMes,
                type: 'error',
                dangerouslyUseHTMLString: true
              })
            }
            return
          }
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.updatePassword()
      }).catch(error => {
        this.loading = false
        this.$message.error(error)
        console.log(error)
      })
    },
    handleIpPortValue () {
      // IP，子网掩码，网关为空时，默认设为0.0.0.0
      // 端口为空时默认改为0
      let customInfo = this.customInfo
      if (!customInfo.centerip) {
        customInfo.centerip = {
          ip: '0.0.0.0',
          port: 0
        }
      }
      if (customInfo.centerip.ip === '') {
        customInfo.centerip.ip = '0.0.0.0'
      }
      if (customInfo.centerip.port === '') {
        customInfo.centerip.port = 0
      }
      customInfo.netcard.forEach(netcard => {
        if (!netcard.ip || netcard.ip === '') {
          netcard.ip = '0.0.0.0'
        }
        if (!netcard.gateway || netcard.gateway === '') {
          netcard.gateway = '0.0.0.0'
        }
        if (!netcard.subnetmask || netcard.subnetmask === '') {
          netcard.subnetmask = '0.0.0.0'
        }
      })
      if (!customInfo.commuport || customInfo.commuport === '') {
        customInfo.commuport = 0
      }
    },
    setLoadingBg () {
      this.loadingBg = getTheme() === 'light' ? 'rgba(255, 255, 255, 0.5)' : 'rgba(32, 41, 64, 0.5)'
    },
    validateSecretkey (rule, value, callback) {
      if (value === '') {
        callback(new Error(this.$t('edge.deviceinfo.secretkeynotnull')))
      } else if (!this.isAlphanumeric(value)) {
        callback(new Error(this.$t('edge.deviceinfo.enterCharacter')))
      } else if (value.length < 8 || value.length > 16) {
        callback(new Error(this.$t('edge.deviceinfo.enterSecretkeylength')))
      } else {
        callback()
      }
    },
    isAlphanumeric (str) {
      return /^[a-zA-Z0-9]+$/.test(str)
    }
  },
  created () {
    this.setLoadingBg()
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
</style>
